#!/bin/bash

# 扫描脚本文件夹,按编号生成用例列表
echo "用例列表："
for i in $(ls ./scripts)	
do  # 截取左边${string%chars*} 截取右边 ${string#*chars}
	case_list[j]=${i%.*}	 											
	#echo -e "\e[32m 	$[$j+1] ${i%.*} \e[0m" 

	export jmx_template=${i%.*}
	export suffix=".jmx"
	export jmx_template_filename="${jmx_template}${suffix}"
	export os_type=`uname`
	export data=`date +%H%M%S%Y%m%d`

	echo "自动化压测准备......"

	# thread_number_array压测并发数列表, duration压测时间, setup_time线程启动时间
	thread_number_array=(10 20)
	duration=20
	ramp_time=1
	for num_threads in "${thread_number_array[@]}"
	do
		# 生成对应压测线程的jmx文件
		export jmx_filename="${jmx_template}_${num_threads}${suffix}"
		export jtl_filename="test_${num_threads}.jtl"
		export web_report_path_name="${jmx_template}_${num_threads}"
		# 清除旧数据
		rm -f testcases/${jmx_filename} results/data/${jtl_filename}
		rm -rf results/reports/${web_report_path_name}
		# 复制并重新命名得到执行脚本文件jmx
		cp scripts/${jmx_template_filename} testcases/${jmx_filename}
		echo "压测脚本${jmx_filename}，线程数${num_threads}，持续时间${duration}S，启动时间${ramp_time}S"
		# 判断执行的操作系统,sed替换做参数化
		if [[ "${os_type}" == "Darwin" ]]; then
			sed -i -e "" 's/ThreadGroup.num_threads">.*</ThreadGroup.num_threads">'${num_threads}'</' -e "" 's/ThreadGroup.duration">.*</ThreadGroup.duration">'${duration}'</' -e "" 's/ThreadGroup.ramp_time">.*</ThreadGroup.ramp_time">'${ramp_time}'</' testcases/${jmx_filename}
		else
			sed -i -e 's/ThreadGroup.num_threads">.*</ThreadGroup.num_threads">'${num_threads}'</' -e 's/ThreadGroup.duration">.*</ThreadGroup.duration">'${duration}'</' -e 's/ThreadGroup.ramp_time">.*</ThreadGroup.ramp_time">'${ramp_time}'</' testcases/${jmx_filename}
		
		echo "自动化压测开始......"
			
		#read -p "请选择测试用例：" input
		fi

		# JMeter 静默压测
		#${jmeter_path}/bin/jmeter -n -t testcases/${jmx_filename} -l results/data/${jtl_filename}
		jmeter -n -t testcases/${jmx_filename} -l results/data/${jtl_filename}
		
		# 生成Web压测报告
		#${jmeter_path}/bin/jmeter -g results/data/${jtl_filename} -e -o results/reports/${web_report_path_name}
		jmeter -g results/data/${jtl_filename} -e -o results/reports/${web_report_path_name}

		rm -f testcases/${jmx_filename} results/data/${jtl_filename}
		echo "========================================================================================"

	done	
done
echo "测试报告目录：${PWD}/results/reports"	
echo "自动化压测全部结束"
